<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <div style="margin: 16px;">
        <van-button round block type="info">登录</van-button>
      </div>
    </van-form>
     <a href="#/enroll">还没有注册？立即注册</a>
  </div>
</template>
<script>
import { mapState, mapMutations } from "vuex";
import qs from "qs";
export default {
  data() {
    return {
      username: "13500000000",
      password: "13888888888",
      flag: true
    };
  },
  methods: {
    async onSubmit() {
      var obj = {
        mobile: this.username,
        pwd: this.password
      };
      let { data: res } = await this.$http.get(
        "https://api.it120.cc/small4/user/m/login?deviceId=007&deviceName=monkey&" +
          qs.stringify(obj)
      );
      console.log(res);
      if (res.msg == "success") {
        this.setToken(res.data.token);
        this.$toast.success("登录成功");
        // 路由跳转
        if (this.flag) {
          this.$router.push("/home");
        } else {
          this.$router.go(-1);
        }
      } else {
        this.$toast.fail(res.msg);
      }
    },
    ...mapMutations(["setToken"])
  },
  component: {
    ...mapState(["token"])
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (from.path != "/user") {
        vm.flag = false;
      }
    });
  }
};
</script>
<style>
a {
  width: 100%;
  display: inline-block;
  text-align: center;
}
</style>